#! /bin/sh

# time zone configuration, default value is Asia/Shanghai
TIME_ZONE=${TIME_ZONE:-"Asia/Shanghai"}
echo "$TIME_ZONE" > /etc/timezone
ln -sf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime

nginx_dir="/etc/nginx/"
DOMAIN=${DOMAIN:-"wp.com"}
nginx_conf_name=`echo $DOMAIN | sed "s/\./_/g"`
php_open_basedir="/opt/webroot/wordpress/"

run_time="/run/nginx/"
sock_dir="/run/sock/"
phpfpm_sock="${sock_dir}php-fpm.sock"

if [ ! -d $run_time ]; then
    mkdir $run_time
fi

if [ ! -d $sock_dir ]; then
    mkdir $sock_dir
    if [ ! -e $phpfpm_sock ]; then
        touch $phpfpm_sock
    fi
    chown nobody:nobody -R $sock_dir
fi

sed -i "s/user nginx;/user nobody nobody;/" /etc/nginx/nginx.conf
if [ -e "${nginx_dir}conf.d/default.conf" ]; then
    rm "${nginx_dir}conf.d/default.conf"
fi

cat > "${nginx_dir}conf.d/${nginx_conf_name}.conf" << EOF
server {
    listen       80;
    #listen       443 ssl;
    server_name  $DOMAIN;
    root   /opt/webroot/wordpress;
    index index.php;

    #ssl on;
    #ssl_certificate   cert/${nginx_conf_name}.pem;
    #ssl_certificate_key  cert/${nginx_conf_name}.key;
    #ssl_session_timeout 5m;
    #ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    #ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    #ssl_prefer_server_ciphers on;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }   

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }   

    location / { 
        try_files \$uri \$uri/ /index.php?\$args;
    }   

    location ~ \\.php$ {
        fastcgi_intercept_errors    on; 
        fastcgi_pass                unix:/run/sock/php-fpm.sock;
        fastcgi_buffers             16 16k;
        fastcgi_buffer_size         32k;
        fastcgi_index               index.php;
        fastcgi_param               SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
        fastcgi_param               PHP_VALUE "open_basedir=${php_open_basedir}";
        include                     fastcgi_params;
    }   

    location ~* \\.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }   

    location ~ ^/\\.user\\.ini {
        deny all;
    }
}
EOF

exec nginx -g 'daemon off;'
